package com.example.validation.common;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 统一异常封装类
 */
@RestControllerAdvice
public class ErrorAdive {

    /**
     * Validation 异常处理
     */
    @ExceptionHandler(value = BindException.class)
    public Object bindExceptionHandler(BindException e) {
        String msg = e.getMessage();
        BindingResult bindingResult = e.getBindingResult();
        // 获取第一个不合法的参数（如果有多个参数不合法的话）
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null) {
            msg = fieldError.getDefaultMessage();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("state", 0);
        map.put("data", null);
        map.put("msg", msg);
        return map;
    }
    
    @ExceptionHandler(Exception.class)
    public Object handler(Exception e) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("state", 0);
        map.put("data", null);
        map.put("msg", e.getMessage());
        return map;
    }
}